﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml;
using System.IO;
using StellarMedical.ServiceReference;
using StellarMedical.DuplexServiceReference;

namespace StellarMedical
{
    public partial class RSSReader : UserControl
    {

        // example: http://www.medicalnewstoday.com/rss/featurednews.xml

        //private DuplexServiceClient serviceRef { get; set; }

        private int itemsLoadedSoFar { get; set; }

        public string FeedURL { get; set; }

        public bool isLoaded { get; set; }

        public int maxItemsToLoad { get; set; }

        //private HttpWebRequest RequestClient { get; set; }

        public RSSReader()
        {
            InitializeComponent();
        }

        // download handler
        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // parse the XML

                if (ItemView.Items.Count > 0)
                {
                    return;
                }

                StringReader strReader = new StringReader(e.Result);
                XmlReader reader = XmlReader.Create(strReader);

                TreeViewItem item = null;
                string titleStr = "";
                while (reader.Read())
                {

                    if (reader.Name == "title")
                    {
                        item = new TreeViewItem();
                        titleStr = reader.ReadInnerXml();
                        ItemView.Items.Add(item);
                    }

 
                    if (reader.Name == "description")
                    {
                        item.Items.Add(new TreeViewItem() {

                            Header = new TextBlock(){

                                Text = reader.ReadInnerXml(),
                                TextWrapping = TextWrapping.Wrap,
                                Width = 280
                            } 
                        });
                    }

                    if (reader.Name == "pubDate")
                    {
                        titleStr += " - " + reader.ReadInnerXml();
                        item.Header = new TextBlock()
                        {
                            Text = titleStr,
                            Style = this.Resources["TitleBlockStyle"] as Style
                        };

                    }
                }

                ItemView.Items.RemoveAt(0);
            }

            
        }



        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            // check to see if we've got a feed
            // stop run
            
            // read the xml


            /*Uri url = new Uri(this.FeedURL, UriKind.Absolute);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.BeginGetResponse(new AsyncCallback(WebComplete), req);
            */

            //TitleBlock.Text = Application.Current.Host.Source.Host;

            //ItemView.Items.Clear();

            WebClient client = new WebClient();
            WebClient clientB = new WebClient();

            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            clientB.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);


            //client.DownloadStringAsync(new Uri("http://localhost:1726/Feed.xml", UriKind.Absolute));

            client.DownloadStringAsync(new Uri("http://stellarmedical.com.au/Feed.xml", UriKind.Absolute));
            clientB.DownloadStringAsync(new Uri("http://www.stellarmedical.com.au/Feed.xml", UriKind.Absolute));

            //XmlReader reader = XmlReader.Create("Feed.xml");

            //reader.ReadInnerXml();

            //TitleBlock.Text = reader.ReadInnerXml();

            //if (!this.isLoaded)
            //{

            //    if (this.FeedURL == null || this.FeedURL == string.Empty || this.FeedURL == "")
            //        return;

            //    //serviceRef = ServiceConfig.DuplexConnect();

            //    //serviceRef.InitiateDuplexCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(serviceRef_InitiateDuplexCompleted);
            //    //serviceRef.BeginFetchDataCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(serviceRef_BeginFetchDataCompleted);
            //    //serviceRef.ReceiveTitleReceived += new EventHandler<ReceiveTitleReceivedEventArgs>(serviceRef_ReceiveTitleReceived);
            //    //serviceRef.ReceiveItemReceived += new EventHandler<ReceiveItemReceivedEventArgs>(serviceRef_ReceiveItemReceived);
            //    //serviceRef.InitiateDuplexAsync();
            //}

        }

     

        //void serviceRef_ReceiveItemReceived(object sender, ReceiveItemReceivedEventArgs e)
        //{
        //    this.itemsLoadedSoFar++;

        //    if (this.itemsLoadedSoFar > this.maxItemsToLoad)
        //        return;

        //    // add the item to the tree view
        //    if (e.Error != null)
        //        return;

        //    HyperlinkButton link = new HyperlinkButton()
        //    {
        //        Content = new TextBlock()
        //        {
        //            TextWrapping = TextWrapping.Wrap,
        //            Text = e.item.Title,
        //            Style = this.Resources["BodyBlockStyle"] as Style
        //        },
        //        NavigateUri = new Uri(e.item.Url, UriKind.Absolute),
        //    };

        //    TextBlock tbTimestamp = new TextBlock()
        //    {
        //        Text = e.item.Timestamp,
        //        TextWrapping = TextWrapping.Wrap,
        //        Style = this.Resources["TimestampBlockStyle"] as Style
        //    };

        //    tbTimestamp.SetValue(Grid.ColumnProperty, 0);
        //    tbTimestamp.SetValue(Grid.RowProperty, 0);

        //    TextBlock tbBody = new TextBlock()
        //    {
        //        Text = e.item.Body,
        //        TextWrapping = TextWrapping.Wrap,
        //        Style = this.Resources["BodyBlockStyle"] as Style
        //    };

        //    tbBody.SetValue(Grid.ColumnProperty, 0);
        //    tbBody.SetValue(Grid.RowProperty, 1);

        //    Grid tpContainer = new Grid();

        //    tpContainer.ColumnDefinitions.Add(new ColumnDefinition());
        //    tpContainer.RowDefinitions.Add(new RowDefinition());
        //    tpContainer.RowDefinitions.Add(new RowDefinition());

        //    tpContainer.Children.Add(tbTimestamp);
        //    tpContainer.Children.Add(tbBody);

        //    TreeViewItem tvItem = new TreeViewItem()
        //    {
        //        Header = link
        //    };


        //    TreeViewItem bodyItem = new TreeViewItem()
        //    {
        //        Header = tpContainer
        //    };

        //    tvItem.Items.Add(bodyItem);

        //    ItemView.Items.Add(tvItem);
        //}

        //void serviceRef_BeginFetchDataCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        //{
        //    this.isLoaded = true;
        //}

        //void serviceRef_ReceiveTitleReceived(object sender, ReceiveTitleReceivedEventArgs e)
        //{
        //    if (e.Error != null)
        //    {
        //        TitleBlock.Text = e.Error.Message;
        //        return;
        //    }

        //    TitleBlock.Text = e.info.Title;
        //}

        //void serviceRef_InitiateDuplexCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        //{
        //    if (e.Error != null)
        //    {
        //        TitleBlock.Text = e.Error.Message;
        //        return;
        //    }

        //    //serviceRef.BeginFetchDataAsync(this.FeedURL);
        //}



    }
}
